package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserLoginService;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.HashMap;

@Service
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserLoginService {

    @Resource
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //判断参数
        if (dto.getEquipmentId()==null&& (StringUtils.isEmpty(dto.getPhone())&&StringUtils.isEmpty(dto.getPassword()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //手机号和密码登录
        if (!StringUtils.isEmpty(dto.getPhone())&&!StringUtils.isEmpty(dto.getPassword())){
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if (apUser!=null){
                String hex = DigestUtils.md5DigestAsHex((dto.getPassword() + apUser.getSalt()).getBytes());
                if (apUser.getPassword().equals(hex)){
                    HashMap<String, Object> map = new HashMap<>();
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));//生产token并保存到map
                    map.put("user",apUser);
                    return ResponseResult.okResult(map);
                }else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
        }else {//设备登录
            if (dto.getEquipmentId()==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }




}
